const express = require('express');
const {uploading, formatResponse} = require("../utils/tool");
const {MulterError} = require("multer");
const {UploadError} = require("../utils/errors");
const router = express.Router();

// 上传图片
router.post('/', async function (req, res, next) {
    //  single 方法内为上传控件的 name 值 同时也是 form-data 的 key 值
    uploading.single('file')(req, res, async function (err) {
        // console.log(req.file)
        if (err instanceof MulterError) {
            next(new UploadError('上传文件失败，请检查文件大小，控制在 2MB 以内'))
        } else {
            res.send(formatResponse(0, "", '/static/uploads/' + req.file.filename))
        }
    })
})

module.exports = router;
